package com.api.config;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.api.domain.UserDTO;
import com.api.entity.Roles;
import com.api.entity.User;
import com.api.entity.UserDept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

import static com.api.entity.table.RolesTableDef.ROLES;
import static com.api.entity.table.UserRoleTableDef.USER_ROLE;

/**
 * @Author: yangsf
 * @CreateDate: 2024/2/23
 */

@Service
public class CachService {

    @Autowired
    RedisService redisService;

    public UserDTO setCachUser(User user){
        UserDTO userDTO = new UserDTO();
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        BeanUtil.copyProperties(user,userDTO);
        userDTO.setUserId(user.getId());
        userDTO.setTokenName(tokenInfo.getTokenName());
        userDTO.setTokenValue(tokenInfo.getTokenValue());
        StpUtil.getSession().set("tokenInfo", tokenInfo);
        StpUtil.getSession().set("userInfo", userDTO);

        //设置角色信息
        Roles role = Roles.create().select(ROLES.ALL_COLUMNS)
                .leftJoin(USER_ROLE).on(USER_ROLE.USER_ID.eq(StpUtil.getLoginIdAsLong())).and(USER_ROLE.STATUS.eq(1))
                .where(ROLES.ID.eq(USER_ROLE.ROLE_ID)).and(ROLES.STATUS.eq(1)).one();
        if(null != role && null != role.getRoleType()){
            userDTO.setRoleId(role.getId());
            userDTO.setRoleType(role.getRoleType());
//            String roleList = RedisConstant.SYS_ROLE_ID + role.getRoleType();
//            SaManager.getSaTokenDao().setObject("satoken:loginId-find-role:" + StpUtil.getLoginId(), roleList, 60 * 60 * 24);
        }
        //设置部门信息
        UserDept ud = UserDept.create().setStatus(1).setUserId(user.getId()).one();
        if(null != ud){
            userDTO.setDeptId(ud.getDeptId());
        }
        redisService.setCacheObject(RedisConstant.USER_INFO + StpUtil.getLoginId(), userDTO, 2L, TimeUnit.HOURS);
        return userDTO;
    }
}
